//
//  HmacUtils.m
//  
//
//  Created by  on 16/7/22.
//  Copyright © 2016年 . All rights reserved.
//
#define RandomDataSource @"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9"
#import "HmacUtils.h"

@implementation HmacUtils

/**
 *  加密方式,MAC算法: HmacSHA256
 *
 *  @param plaintext 要加密的文本
 *  @param key       秘钥
 *
 *  @return 加密后的字符串
 */
+ (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key
{
    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
    NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
    for (int i = 0; i < HMACData.length; ++i){
        [HMAC appendFormat:@"%02x", buffer[i]];
    }
    
    return HMAC;
}

/**
 *  @author zhao, 16-07-22 15:07:29
 *
 *  se
 *
 *  @return 伪随机数
 */
+(NSString*)getSeRandomkey{

    NSArray *array = [RandomDataSource componentsSeparatedByString:@","];
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<32; i++) {
        [str appendString:array[(int)(arc4random()%62)]];
    }

    return str;
}

@end
